package com.hethongviet.job.pages;

import group.pals.android.lib.ui.filechooser.FileChooserActivity;
import group.pals.android.lib.ui.filechooser.io.LocalFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.hethongviet.job.AppMain;
import com.hethongviet.job.Config;
import com.hethongviet.job.Connectivity;
import com.hethongviet.job.R;
import com.hethongviet.job.helpers.CodeResult;
import com.hethongviet.job.helpers.ComparableHelper.CommentCompartorByDateCreateDown;
import com.hethongviet.job.helpers.ComparableHelper.CommentCompartorByDateCreateUp;
import com.hethongviet.job.helpers.ComparableHelper.CommentCompartorBySenderDown;
import com.hethongviet.job.helpers.ComparableHelper.CommentCompartorBySenderUp;
import com.hethongviet.job.helpers.ServiceHelper;
import com.hethongviet.job.helpers.TabMenu;
import com.hethongviet.job.helpers.database.CommentSQLite;
import com.hethongviet.job.helpers.database.TaskSQLite;
import com.hethongviet.job.helpers.download.DownloadFile;
import com.hethongviet.job.helpers.listadapter.ListItemCommentAdapter;
import com.hethongviet.job.models.FileImage;
import com.hethongviet.job.models.Tab;
import com.hethongviet.job.models.Task;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap.CompressFormat;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

@TargetApi(5)
public class DetailTaskActivity extends Activity
{
	private LinearLayout _linearLayoutDetail = null;
	private LinearLayout _linearLayoutListComments = null;
	private LinearLayout _linearLayoutGuide = null;

	private Button _buttonImageStart = null;
	private Button _buttonImageStartAgain = null;
	private Button _buttonImageFinish = null;
	private Button _buttonImageFinishAgain = null;
	private TextView _textImageStartStatus = null;
	private TextView _textImageFinishStatus = null;
	private TextView _textDateActualStart = null;
	private TextView _textDateActualFinish = null;

	private Button _buttonGuildDownload = null;

	private ListView _listViewTaskComments = null;
	private ListItemCommentAdapter _listViewItemCommentAdapter = null;

	private TabMenu _tabMenu = null;
	private Button _buttonTabDetail = null;
	private Button _buttonTabListComments = null;
	private Button _buttonTabGuild = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		AppMain.prepareWindow(this);

		setContentView(R.layout.page_detail_task);
		AppMain.showTaskTitle(this);

		/* Tab menu */
		_buttonTabDetail = (Button) findViewById(R.id.buttonTabDetail);
		_buttonTabListComments = (Button) findViewById(R.id.buttonTabListComments);
		_buttonTabGuild = (Button) findViewById(R.id.buttonTabGuild);

		_linearLayoutDetail = (LinearLayout) findViewById(R.id.layoutTabDetails);
		_linearLayoutListComments = (LinearLayout) findViewById(R.id.layoutTabListComments);
		_linearLayoutGuide = (LinearLayout) findViewById(R.id.layoutTabGuide);

		int totalTab = Config.IS_SALESMAN ? AppMain.TOTAL_TAB_DETAIL_TASK_PAGE - 1
				: AppMain.TOTAL_TAB_DETAIL_TASK_PAGE;

		Tab[] tabs = new Tab[totalTab];
		for (int i = 0; i < totalTab; i++)
		{
			tabs[i] = new Tab();
		}

		tabs[AppMain.TAB_TASK_DETAIL].setButton(_buttonTabDetail);
		tabs[AppMain.TAB_TASK_DETAIL].setLinearLayout(_linearLayoutDetail);

		_buttonTabListComments.setText(String.format(
				getString(R.string.textListComments),
				AppMain._listComments.size()));

		tabs[AppMain.TAB_TASK_COMMENT].setButton(_buttonTabListComments);
		// tabs[AppMain.TAB_TASK_COMMENT].setImplementEventAfter(true);
		tabs[AppMain.TAB_TASK_COMMENT].setLinearLayout(_linearLayoutListComments);
		// _buttonTabListComments.setOnClickListener(new OnClickListener() {
		// public void onClick(View arg0)
		// {
		// //get comments
		// }
		// });

		if (!Config.IS_SALESMAN)
		{
			tabs[AppMain.TAB_TASK_FILE].setButton(_buttonTabGuild);

			tabs[AppMain.TAB_TASK_FILE].setLinearLayout(_linearLayoutGuide);
		}

		_tabMenu = new TabMenu(tabs, R.drawable.button_tab2,
				R.drawable.button_tab2_highlight);

		/* Tab of task details */
		((TextView) findViewById(R.id.textTaskDescription)).setText(AppMain.getCurrentTask().getDescription());
		((TextView) findViewById(R.id.textTaskImportantLevel)).setText(AppMain.getCurrentTask().getImportantLevel());
		((TextView) findViewById(R.id.textTaskDateCreate)).setText(AppMain.getCurrentTask().getDateCreated());
		((TextView) findViewById(R.id.textTaskDateMustFinish)).setText(AppMain.getCurrentTask().getDateRequireFinish());
		((TextView) findViewById(R.id.textTaskDateMustStart)).setText(AppMain.getCurrentTask().getDateRequireStart());
		((TextView) findViewById(R.id.textTaskNote)).setText(AppMain.getCurrentTask().getNote());
		((TextView) findViewById(R.id.textTaskStatus)).setText(AppMain.getCurrentTask().getStatusString(
				this));
		((TextView) findViewById(R.id.textTaskWorker)).setText(AppMain.getCurrentTask().getWorker());

		_textDateActualFinish = (TextView) findViewById(R.id.textTaskDateActualFinish);
		_textDateActualFinish.setText(AppMain.getCurrentTask().getDateActualFinish());
		_textDateActualStart = (TextView) findViewById(R.id.textTaskDateActualStart);
		_textDateActualStart.setText(AppMain.getCurrentTask().getDateActualStart());

		if (AppMain.getCurrentTask().getWorkerGPSGeoPointFinish() != null)
		{
			((TextView) findViewById(R.id.textTaskGPSFinish)).setText("("
					+ AppMain.getCurrentTask().getWorkerGPSGeoPointFinish().getLatitudeE6()
					/ 1E6
					+ ","
					+ AppMain.getCurrentTask().getWorkerGPSGeoPointFinish().getLongitudeE6()
					/ 1E6 + ")");
		}
		else
		{
			((TextView) findViewById(R.id.textTaskGPSFinish)).setText("");
		}

		if (AppMain.getCurrentTask().getWorkerGPSGeoPointStart() != null)
		{
			((TextView) findViewById(R.id.textTaskGPSStart)).setText("("

					+ AppMain.getCurrentTask().getWorkerGPSGeoPointStart().getLatitudeE6()
					/ 1E6
					+ ","
					+ AppMain.getCurrentTask().getWorkerGPSGeoPointStart().getLongitudeE6()
					/ 1E6 + ")");
		}
		else
		{
			((TextView) findViewById(R.id.textTaskGPSStart)).setText("");
		}

		/* Images */
		processImage();

		/* Tab of task comments */
		_listViewTaskComments = (ListView) findViewById(R.id.listViewComments);

		/* Show the list of tasks */
		_listViewItemCommentAdapter = new ListItemCommentAdapter(
				DetailTaskActivity.this, AppMain._listComments);
		_listViewTaskComments.setAdapter(_listViewItemCommentAdapter);
		_listViewTaskComments.setTextFilterEnabled(true);
		_listViewTaskComments.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				AppMain._currentIndexComment = position;
				if (Config.USE_COMMENT_MARK_UNREAD
						&& !AppMain.getCurrentComment().isRead())
				{
					AppMain.getCurrentComment().setRead(true);
					CommentSQLite commentSQLite = new CommentSQLite(
							DetailTaskActivity.this);
					commentSQLite.updateRead(AppMain.getCurrentComment());
				}
				Intent intent = new Intent(DetailTaskActivity.this,
						DetailCommentActivity.class);
				startActivity(intent);

			}
		});

		processDialogListSortingComment(AppMain.SORT_COMMENT_DATE_CREATE_DOWN);

		/* Guide tab */
		_buttonGuildDownload = (Button) findViewById(R.id.buttonTaskGuideFile);
		((TextView) findViewById(R.id.textTaskGuide)).setText(AppMain.getCurrentTask().getGuideText());

		if (Config.ENABLE_DOWNLOAD_FILE
				&& AppMain.getCurrentTask().getFileAttachment() != null
				&& !TextUtils.isEmpty(AppMain.getCurrentTask().getFileAttachment().getName()))
		{
			_buttonGuildDownload.setVisibility(View.VISIBLE);
			_buttonGuildDownload.setOnClickListener(new OnClickListener()
			{
				public void onClick(View arg0)
				{
					AppMain.showFileChooser(DetailTaskActivity.this,
							AppMain.REQUEST_CHOOSE_DIRECTORY);
				}
			});
		}
		else
			_buttonGuildDownload.setVisibility(View.GONE);

		AppMain.registerGPS(this);
	}

	private void processImage()
	{
		_textImageStartStatus = (TextView) findViewById(R.id.textTaskImageStartStatus);
		_buttonImageStart = (Button) findViewById(R.id.buttonTaskChoosingImageStart);
		_buttonImageStartAgain = (Button) findViewById(R.id.buttonTaskChoosingImageStartAgain);

		_buttonImageStartAgain.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				AppMain.showDialogList(DetailTaskActivity.this,
						AppMain.DIALOG_CHOOSING_IMAGE);
			}
		});

		_textImageFinishStatus = (TextView) findViewById(R.id.textTaskImageFinishStatus);
		_buttonImageFinish = (Button) findViewById(R.id.buttonTaskChoosingImageFinish);
		_buttonImageFinishAgain = (Button) findViewById(R.id.buttonTaskChoosingImageFinishAgain);

		_buttonImageFinishAgain.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				AppMain.showDialogList(DetailTaskActivity.this,
						AppMain.DIALOG_CHOOSING_IMAGE);
			}
		});

		if (!AppMain.getCurrentTask().isStarted())// not start yet
		{
			_textImageStartStatus.setText(getString(R.string.textNotYes));
			_textImageStartStatus.setVisibility(View.VISIBLE);
			_buttonImageStart.setText(getString(R.string.textChoosingImage));
			_buttonImageStart.setOnClickListener(new OnClickListener()
			{
				public void onClick(View v)
				{
					if (AppMain._imageFileTemporaryTaskStart != null) // just
																		// chose
																		// image
					{
						AppMain._imageFileView = AppMain._imageFileTemporaryTaskStart;
						Intent intent = new Intent(DetailTaskActivity.this,
								ViewImageActivity.class);
						intent.putExtra("request_type",
								AppMain.REQUEST_VIEW_IMAGE);
						startActivityForResult(intent,
								AppMain.REQUEST_VIEW_IMAGE);
						AppMain.getCurrentTask().setViewImageStart(true);
					}
					else
						AppMain.showDialogList(DetailTaskActivity.this,
								AppMain.DIALOG_CHOOSING_IMAGE);
				}
			});

			_buttonImageStart.setVisibility(View.VISIBLE);

			_textImageFinishStatus.setText(getString(R.string.textNotYes));
			_textImageFinishStatus.setVisibility(View.VISIBLE);
			_buttonImageFinish.setVisibility(View.GONE);
		}
		else
		// started
		{
			/* Start image */
			if (AppMain.getCurrentTask().getImageFileStart() != null
					&& !TextUtils.isEmpty(AppMain.getCurrentTask().getImageFileStart().getName()))
			{
				_textImageStartStatus.setVisibility(View.GONE);
				_buttonImageStart.setText(getString(R.string.textViewImage));
				_buttonImageStart.setOnClickListener(new OnClickListener()
				{
					public void onClick(View v)
					{
						String imageName = AppMain.getCurrentTask().getImageFileStart().getName();
						AppMain._imageFileView = (AppMain._imageFileTemporaryTaskStart != null) ? AppMain._imageFileTemporaryTaskStart
								: new FileImage(null, imageName, null, null);
						if (imageName.length() > 3)
						{
							Intent intent = new Intent(DetailTaskActivity.this,
									ViewImageActivity.class);
							intent.putExtra("request_type",
									AppMain.REQUEST_DOWNLOAD_IMAGE);
							startActivityForResult(intent,
									AppMain.REQUEST_VIEW_IMAGE);
							AppMain.getCurrentTask().setViewImageStart(true);
						}
						else
						{
							AppMain.showAlert(DetailTaskActivity.this,
									R.string.textErrorFileDamaged, false);
						}
					}
				});
				_buttonImageStart.setVisibility(View.VISIBLE);
			}
			else
			{
				_textImageStartStatus.setText(getString(R.string.textNone));
				_textImageStartStatus.setVisibility(View.VISIBLE);
				_buttonImageStart.setVisibility(View.GONE);
			}
			/* Finish image */
			if (!AppMain.getCurrentTask().isFinished())// Not finish yet
			{
				_textImageFinishStatus.setText(getString(R.string.textNotYes));
				_textImageFinishStatus.setVisibility(View.VISIBLE);
				_buttonImageFinish.setText(getString(R.string.textChoosingImage));
				_buttonImageFinish.setOnClickListener(new OnClickListener()
				{
					public void onClick(View v)
					{
						if (AppMain._imageFileTemporaryTaskFinish != null) // just
																			// choosing
																			// image
						{
							AppMain._imageFileView = AppMain._imageFileTemporaryTaskFinish;
							Intent intent = new Intent(DetailTaskActivity.this,
									ViewImageActivity.class);
							intent.putExtra("request_type",
									AppMain.REQUEST_VIEW_IMAGE);
							startActivityForResult(intent,
									AppMain.REQUEST_VIEW_IMAGE);
							AppMain.getCurrentTask().setViewImageStart(false);

						}
						else
							AppMain.showDialogList(DetailTaskActivity.this,
									AppMain.DIALOG_CHOOSING_IMAGE);
					}
				});
				_buttonImageFinish.setVisibility(View.VISIBLE);
			}
			else
			// Finished
			{
				if (AppMain.getCurrentTask().getImageFileFinish() != null
						&& !TextUtils.isEmpty(AppMain.getCurrentTask().getImageFileFinish().getName()))
				{
					_textImageFinishStatus.setVisibility(View.GONE);
					_buttonImageFinish.setText(getString(R.string.textViewImage));
					_buttonImageFinish.setOnClickListener(new OnClickListener()
					{
						public void onClick(View v)
						{
							String imageName = AppMain.getCurrentTask().getImageFileFinish().getName();
							AppMain._imageFileView = (AppMain._imageFileTemporaryTaskFinish != null) ? AppMain._imageFileTemporaryTaskFinish
									: new FileImage(null, imageName, null, null);

							if (imageName.length() > 3)
							{
								Intent intent = new Intent(
										DetailTaskActivity.this,
										ViewImageActivity.class);
								intent.putExtra("request_type",
										AppMain.REQUEST_DOWNLOAD_IMAGE);
								startActivityForResult(intent,
										AppMain.REQUEST_VIEW_IMAGE);
								AppMain.getCurrentTask().setViewImageStart(
										false);
							}
							else
							{
								AppMain.showAlert(DetailTaskActivity.this,
										R.string.textErrorFileDamaged, false);
							}
						}
					});
					_buttonImageFinish.setVisibility(View.VISIBLE);
				}
				else
				{
					_textImageFinishStatus.setText(getString(R.string.textNone));
					_textImageFinishStatus.setVisibility(View.VISIBLE);
					_buttonImageFinish.setVisibility(View.GONE);
				}
			}
		}
	}

	@Override
	protected void onResume()
	{
		AppMain.debug("Detail task resume!!!!!!!!!!!");
		super.onResume();
		refreshListComments();
		if (AppMain._numberBackWhenLogout > 0)
		{
			AppMain._numberBackWhenLogout--;
			// finish();
			onBackPressed();
		}
	}

	@Override
	public void onBackPressed()
	{
		AppMain.removeGPS();
		super.onBackPressed();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		MenuInflater menuInflater = getMenuInflater();
		if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK_DETAIL)
		{
			menuInflater.inflate(R.menu.menu_option_task_detail, menu);
			if (AppMain.getCurrentTask().isStarted())
			{
				menu.findItem(R.id.menuItemTaskDetailStart).setEnabled(false);
			}
			else
			{
				menu.findItem(R.id.menuItemTaskDetailFinish).setEnabled(false);
			}

			if (AppMain.getCurrentTask().isFinished())
			{
				menu.findItem(R.id.menuItemTaskDetailFinish).setEnabled(false);
			}
		}
		else if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK_COMMENT)
			menuInflater.inflate(R.menu.menu_option_task_detail_comment, menu);
		else
			menuInflater.inflate(R.menu.menu_option_task_detail_guide, menu);
		return super.onPrepareOptionsMenu(menu);
	}

	private void doAction(final FileImage imageFile, final boolean isStart,
			final int prefix)
	{
		AppMain.showProgress(DetailTaskActivity.this);
		new Thread(new Runnable()
		{

			public void run()
			{
				String imageName = null;
				/* Rename the image name */
				if (imageFile != null)
				{
					String fileName = imageFile.getName();
					imageName = AppMain.getFileNameFormat(prefix,
							AppMain.getFileType(fileName));
				}

				String resultTasksString = null;
				boolean isSyncData = true;

				if (isStart)
				{

					if (TextUtils.isEmpty(imageName))
					{
						resultTasksString = ServiceHelper.doStartTask(
								AppMain._user.getMemberId(), "", null,
								AppMain.getCurrentTask().getId(),
								AppMain._currentLatitude,
								AppMain._currentLongitude);
					}
					else if (!Connectivity.isConnectedFast(DetailTaskActivity.this))
					{
						AppMain.debug("Send network slowly!!!");

						resultTasksString = ServiceHelper.doStartTaskLowNetwork(
								AppMain._user.getMemberId(),
								AppMain.getCurrentTask().getId(),
								AppMain._currentLatitude,
								AppMain._currentLongitude);

						File file = new File(imageFile.getPath() + "/"
								+ imageFile.getName());

						AppMain.debug("copy image, file exist? "
								+ file.exists());

						if (file.exists())
						{
							imageFile.setBitmap(AppMain.getBitmapFromFile(
									DetailTaskActivity.this, file));
						}
						
						AppMain.debug("image name = "
								+ imageFile.getName()
								+ "bitmap = "
								+ (imageFile.getBitmap() != null ? "(...)"
										: "null"));
						
						imageFile.setName(imageName);
						
						if (imageFile.getBitmap() != null)
						{

							imageFile.setPath(Environment.getExternalStorageDirectory().getPath()
									+ AppMain.DIRECTORY_DATA_SAVE);

							AppMain.debug("@@@@@@@@@@@  copyImageFile to "
									+ imageFile.getPath() + "/"
									+ imageFile.getName());

							File directory = new File(imageFile.getPath());
							if (!directory.exists())
							{
								directory.mkdir();
							}

							File newFile = new File(imageFile.getPath() + "/"
									+ imageFile.getName());

							if (newFile.exists())
							{
								newFile.delete();
							}

							try
							{
								newFile.createNewFile();
							} catch (IOException e1)
							{
								e1.printStackTrace();
							}

							FileOutputStream fileOutputStream;
							try
							{
								fileOutputStream = new FileOutputStream(newFile);
								imageFile.getBitmap().compress(
										CompressFormat.JPEG, 100,
										fileOutputStream);
							} catch (FileNotFoundException e)
							{
								e.printStackTrace();
							}
						}

						isSyncData = false;
					}
					else
					{
						String imageData = AppMain.getStringImageData(
								imageFile, true);
						if (imageData.equals(ServiceHelper.ERROR_OUT_OF_MEMORY))
						{
							AppMain._codeResultService = CodeResult.ERROR_OUT_OF_MEMORY;
							AppMain.hideProgressDialog();
							return;
						}
						resultTasksString = ServiceHelper.doStartTask(
								AppMain._user.getMemberId(), imageName,
								imageData, AppMain.getCurrentTask().getId(),
								AppMain._currentLatitude,
								AppMain._currentLongitude);
						
						isSyncData = true;
					}
				}
				else
				{

					if (TextUtils.isEmpty(imageName))
					{
						resultTasksString = ServiceHelper.doFinishTask(
								AppMain._user.getMemberId(), "", null,
								AppMain.getCurrentTask().getId(),
								AppMain._currentLatitude,
								AppMain._currentLongitude);
					}
					else if (!Connectivity.isConnectedFast(DetailTaskActivity.this))
					{
						AppMain.debug("Send network slowly!!!");

						resultTasksString = ServiceHelper.doFinishTaskLowNetwork(
								AppMain._user.getMemberId(),
								AppMain.getCurrentTask().getId(),
								AppMain._currentLatitude,
								AppMain._currentLongitude);

						File file = new File(imageFile.getPath() + "/"
								+ imageFile.getName());

						AppMain.debug("copy image, file exist? "
								+ file.exists());

						if (file.exists())
						{
							imageFile.setBitmap(AppMain.getBitmapFromFile(
									DetailTaskActivity.this, file));
						}

						AppMain.debug("image name = "
								+ imageFile.getName()
								+ "bitmap = "
								+ (imageFile.getBitmap() != null ? "(...)"
										: "null"));
						
						imageFile.setName(imageName);
						
						if (!TextUtils.isEmpty(imageFile.getName())
								&& imageFile.getBitmap() != null)
						{

							imageFile.setPath(Environment.getExternalStorageDirectory().getPath()
									+ AppMain.DIRECTORY_DATA_SAVE);

							AppMain.debug("@@@@@@@@@@@  copyImageFile to "
									+ imageFile.getPath() + "/"
									+ imageFile.getName());

							File directory = new File(imageFile.getPath());
							if (!directory.exists())
							{
								directory.mkdir();
							}

							File newFile = new File(imageFile.getPath() + "/"
									+ imageFile.getName());

							if (newFile.exists())
							{
								newFile.delete();
							}

							try
							{
								newFile.createNewFile();
							} catch (IOException e1)
							{
								e1.printStackTrace();
							}

							FileOutputStream fileOutputStream;
							try
							{
								fileOutputStream = new FileOutputStream(newFile);
								imageFile.getBitmap().compress(
										CompressFormat.JPEG, 100,
										fileOutputStream);
							} catch (FileNotFoundException e)
							{
								e.printStackTrace();
							}
						}

						isSyncData = false;
					}
					else
					{
						String imageData = AppMain.getStringImageData(
								imageFile, true);
						if (imageData.equals(ServiceHelper.ERROR_OUT_OF_MEMORY))
						{
							AppMain._codeResultService = CodeResult.ERROR_OUT_OF_MEMORY;
							AppMain.hideProgressDialog();
							return;
						}
						resultTasksString = ServiceHelper.doFinishTask(
								AppMain._user.getMemberId(), imageName,
								imageData, AppMain.getCurrentTask().getId(),
								AppMain._currentLatitude,
								AppMain._currentLongitude);

						isSyncData = true;
					}
				}

				String[] splitString = resultTasksString.split("[,]");

				if (splitString[0].equalsIgnoreCase(ServiceHelper.RESULT_OK))
				{
					AppMain._codeResultService = isStart ? CodeResult.SUCCESS_START_TASK
							: CodeResult.SUCCESS_FINISH_TASK;

					if (imageName != null)
					{
						imageFile.setName(imageName);
					}

					String date = null;
					if (splitString.length == 2)
					{
						date = splitString[1];
					}
					else
					{
						Date d = new Date();
						DateFormat dateFormat = new SimpleDateFormat(
								"dd/MM/yyyy kk:mm");
						date = dateFormat.format(d);
					}

					if (isStart)
					{
						AppMain.getCurrentTask().setDateActualStart(
								(date == null ? "" : date));
					}
					else
					{
						AppMain.getCurrentTask().setDateActualFinish(
								(date == null ? "" : date));
					}

					if (isStart)
					{
						AppMain.getCurrentTask().setSyncDataStart(isSyncData);
					}
					else
					{
						AppMain.getCurrentTask().setSyncDataFinish(isSyncData);
					}

					TaskSQLite taskSQLite = new TaskSQLite(
							DetailTaskActivity.this);
					taskSQLite.update(AppMain.getCurrentTask());
				}
				else
				{
					AppMain._codeResultService = isStart ? CodeResult.FAIL_START_TASK
							: CodeResult.FAIL_FINISH_TASK;
				}
				AppMain.hideProgressDialog();
			}
		}).start();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.menuItemSkype)
		{
			AppMain.startSkype(this);
		}
		else if (item.getItemId() == R.id.menuItemAcount)
		{
			AppMain.showDialogList(this, AppMain.DIALOG_ACCOUNT);
		}
		else
		{
			if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK_DETAIL)
			{
				if (item.getItemId() == R.id.menuItemTaskDetailFinish)
				{
					OnClickListener onClickListenerYES = new OnClickListener()
					{
						public void onClick(View v)
						{
							AppMain.hideAllDialog();
							if (AppMain._isSMSEnable)
							{
								OnClickListener onClickListenerYES = new OnClickListener()
								{
									public void onClick(View v)
									{
										AppMain.debug("finish job by SMS!!!!!!!");
										AppMain.hideAllDialog();
										if (Config.IS_DEBUG)
											AppMain.sendSMS(
													DetailTaskActivity.this,
													Config.SMS_DEBUG_NUMBER,
													Config.SMS_DEBUG_MESSAGE_FINISH
															+ ","
															+ AppMain._currentLatitude
															+ ","
															+ AppMain._currentLongitude);
										else
										{

										}
									}
								};
								AppMain.showAlert(DetailTaskActivity.this,
										R.string.textMessageSMSAvailableFinish,
										false, onClickListenerYES);
							}
							else
							{
								LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
								if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
								{
									OnClickListener onClickListenerYES = new OnClickListener()
									{
										public void onClick(View v)
										{
											AppMain.hideAllDialog();
											// Launch settings, allowing user to
											// make a change
											Intent i = new Intent(
													Settings.ACTION_LOCATION_SOURCE_SETTINGS);
											startActivity(i);
										}
									};

									OnClickListener onClickListenerNO = new OnClickListener()
									{
										public void onClick(View v)
										{
											AppMain.hideAllDialog();
											doAction(
													AppMain._imageFileTemporaryTaskFinish,
													false,
													AppMain.PREFIX_TASK_DETAIL_FINISH);
										}
									};
									AppMain.showAlert(DetailTaskActivity.this,
											R.string.textMessageEnableGPS,
											false, onClickListenerYES,
											onClickListenerNO);
								}
								else
								{
									doAction(
											AppMain._imageFileTemporaryTaskFinish,
											false,
											AppMain.PREFIX_TASK_DETAIL_FINISH);
								}
							}
						}
					};
					AppMain.showAlert(this,
							R.string.textMessageConfirmFinishTask, false,
							onClickListenerYES);
				}
				else if (item.getItemId() == R.id.menuItemTaskDetailStart)
				{
					OnClickListener onClickListenerYES = new OnClickListener()
					{
						public void onClick(View v)
						{
							AppMain.hideAllDialog();
							if (AppMain._isSMSEnable)
							{
								OnClickListener onClickListenerYES = new OnClickListener()
								{
									public void onClick(View v)
									{
										AppMain.debug("start job by SMS!!!!!!!");
										AppMain.hideAllDialog();
										if (Config.IS_DEBUG)
											AppMain.sendSMS(
													DetailTaskActivity.this,
													Config.SMS_DEBUG_NUMBER,
													Config.SMS_DEBUG_MESSAGE_START
															+ ","
															+ AppMain._currentLatitude
															+ ","
															+ AppMain._currentLongitude);
										else
										{

										}
									}
								};
								AppMain.showAlert(DetailTaskActivity.this,
										R.string.textMessageSMSAvailableStart,
										false, onClickListenerYES);
							}
							else
							{
								LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
								if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
								{
									OnClickListener onClickListenerYES = new OnClickListener()
									{
										public void onClick(View v)
										{
											AppMain.hideAllDialog();
											Intent i = new Intent(
													Settings.ACTION_LOCATION_SOURCE_SETTINGS);
											startActivity(i);
										}
									};

									OnClickListener onClickListenerNO = new OnClickListener()
									{
										public void onClick(View v)
										{
											AppMain.hideAllDialog();
											doAction(
													AppMain._imageFileTemporaryTaskStart,
													true,
													AppMain.PREFIX_TASK_DETAIL_START);
										}
									};
									AppMain.showAlert(DetailTaskActivity.this,
											R.string.textMessageEnableGPS,
											false, onClickListenerYES,
											onClickListenerNO);
								}
								else
								{
									doAction(
											AppMain._imageFileTemporaryTaskStart,
											true,
											AppMain.PREFIX_TASK_DETAIL_START);
								}

							}
						}
					};
					AppMain.showAlert(this,
							R.string.textMessageConfirmStartTask, false,
							onClickListenerYES);
				}
			}
			else if (_tabMenu.getCurrentButtonActive() == AppMain.TAB_TASK_COMMENT)
			{
				if (item.getItemId() == R.id.menuItemTaskDetailCommentAdd)
				{
					// if (AppMain._isSMSEnable)
					// {
					// AppMain.showAlert(this,
					// R.string.textMessageSMSAvailableAddComment,
					// false);
					// }
					// else
					{
						Intent intent = new Intent(DetailTaskActivity.this,
								AddCommentActivity.class);
						startActivityForResult(intent,
								AppMain.REQUEST_ADD_COMMENT);
					}
				}
				else if (item.getItemId() == R.id.menuItemTaskDetailCommentRefresh)
				{
					if (AppMain._isSMSEnable)
					{
						AppMain.showAlert(this,
								R.string.textMessageSMSAvailableRefresh, false);
					}
					else
					{
						showProgressBar();
						new Thread(new Runnable()
						{
							public void run()
							{
								AppMain._codeResultService = AppMain.doGetCommentsByTask(
										DetailTaskActivity.this,
										AppMain.getCurrentTask().getId());
								AppMain.hideProgressDialog();
							}
						}).start();
					}
				}
				else if (item.getItemId() == R.id.menuItemTaskDetailCommentSort)
				{
					AppMain.showDialogList(this, AppMain.DIALOG_FILTER_COMMENT);
				}
			}
			else
			/* Tab guild */
			{
			}
		}
		return true;
	}

	public void processDialogListSortingComment(int itemIndex)
	{
		if (AppMain._listComments.size() < 2)
			return;
		switch (itemIndex)
		{
		case AppMain.SORT_COMMENT_DATE_CREATE_DOWN:
			CommentCompartorByDateCreateDown commentCompartorByDateCreateDown = new CommentCompartorByDateCreateDown();
			Collections.sort(AppMain._listComments,
					commentCompartorByDateCreateDown);
			break;
		case AppMain.SORT_COMMENT_DATE_CREATE_UP:
			CommentCompartorByDateCreateUp commentCompartorByDateCreateUp = new CommentCompartorByDateCreateUp();
			Collections.sort(AppMain._listComments,
					commentCompartorByDateCreateUp);
			break;
		case AppMain.SORT_COMMENT_SENDER_DOWN:
			CommentCompartorBySenderDown commentCompartorBySenderDown = new CommentCompartorBySenderDown();
			Collections.sort(AppMain._listComments,
					commentCompartorBySenderDown);
			break;
		case AppMain.SORT_COMMENT_SENDER_UP:
			CommentCompartorBySenderUp commentCompartorBySenderUp = new CommentCompartorBySenderUp();
			Collections.sort(AppMain._listComments, commentCompartorBySenderUp);
			break;

		default:
			break;
		}
		refreshListComments();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
		case AppMain.REQUEST_CHOOSE_FILE_IMAGE:
			if (resultCode == RESULT_OK)
			{
				AppMain._imageFileView = AppMain.getBitmapFromIntent(this, data);
				if (AppMain._imageFileView != null)
				{
					Intent intent = new Intent(this, ViewImageActivity.class);
					intent.putExtra("request_type",
							AppMain.REQUEST_CHOOSE_FILE_IMAGE);
					startActivityForResult(intent, AppMain.REQUEST_VIEW_IMAGE);
				}
			}
			break;
		case AppMain.REQUEST_CHOOSE_DIRECTORY:
			if (resultCode == RESULT_OK)
			{
				List<LocalFile> localFiles = (List<LocalFile>) data.getSerializableExtra(FileChooserActivity.Results);
				File directory = localFiles.get(0);

				showDialog(AppMain.DIALOG_DOWNLOAD_PROGRESS);

				AppMain.downloadAndSave(this, _progressDialog,
						ServiceHelper.URL_DOWNLOAD_FILE,
						directory.getAbsolutePath(),
						AppMain.getCurrentTask().getFileAttachment().getName());

				AppMain.getCurrentTask().getFileAttachment().setPath(
						directory.getAbsolutePath());

			}
			break;
		case AppMain.REQUEST_CAMERA:
			if (resultCode == RESULT_OK)// ->View image
			{
				AppMain._imageFileView = AppMain.closeCamera(this, data);
				if (Config.IS_USE_VIEW_IMAGE)
				{
					Intent intent = new Intent(this, ViewImageActivity.class);
					intent.putExtra("request_type", AppMain.REQUEST_CAMERA);
					startActivityForResult(intent, AppMain.REQUEST_VIEW_IMAGE);
				}
				else
				{
					if (!AppMain.getCurrentTask().isStarted())
					{
						AppMain._imageFileTemporaryTaskStart = AppMain._imageFileView;
						_textImageStartStatus.setVisibility(View.GONE);
						_buttonImageStart.setText(getString(R.string.textViewImage));
						_buttonImageStart.setVisibility(View.VISIBLE);
						_buttonImageStartAgain.setVisibility(View.VISIBLE);
					}
					else if (!AppMain.getCurrentTask().isFinished())
					{
						AppMain._imageFileTemporaryTaskFinish = AppMain._imageFileView;
						_textImageFinishStatus.setVisibility(View.GONE);
						_buttonImageFinish.setText(getString(R.string.textViewImage));
						_buttonImageFinish.setVisibility(View.VISIBLE);
						_buttonImageFinishAgain.setVisibility(View.VISIBLE);
					}
					AppMain._imageFileView = null;
				}
			}
			else
			// Back
			{
				AppMain._imageFileView = null;
				if (AppMain._codeResultService == CodeResult.FAIL_OPEN_CAMERA)
				{
					AppMain.showAlert(this, R.string.textErrorCameraFailOpen,
							false);
				}
			}
			break;
		case AppMain.REQUEST_ADD_COMMENT:
			if (resultCode == RESULT_OK)// ->View image
			{
				refreshListComments();
			}
			break;
		case AppMain.REQUEST_VIEW_IMAGE:
			if (resultCode == RESULT_OK)// ->View image
			{
				if (!AppMain.getCurrentTask().isStarted())
				{
					AppMain._imageFileTemporaryTaskStart = AppMain._imageFileView;
					_textImageStartStatus.setVisibility(View.GONE);
					_buttonImageStart.setText(getString(R.string.textViewImage));
					_buttonImageStart.setVisibility(View.VISIBLE);
					_buttonImageStartAgain.setVisibility(View.VISIBLE);
				}
				else if (!AppMain.getCurrentTask().isFinished())
				{
					AppMain._imageFileTemporaryTaskFinish = AppMain._imageFileView;
					_textImageFinishStatus.setVisibility(View.GONE);
					_buttonImageFinish.setText(getString(R.string.textViewImage));
					_buttonImageFinish.setVisibility(View.VISIBLE);
					_buttonImageFinishAgain.setVisibility(View.VISIBLE);
				}
			}
			else
			{
				if (AppMain.getCurrentTask().isStarted())
				{
					if (AppMain.getCurrentTask().isViewImageStart())
					{
						AppMain._imageFileTemporaryTaskStart = AppMain._imageFileView;
					}
					else
					{
						if (AppMain.getCurrentTask().isFinished())
						{
							AppMain._imageFileTemporaryTaskFinish = AppMain._imageFileView;
						}
					}
				}
			}
			AppMain._imageFileView = null;
			break;
		default:
			break;
		}
	}

	@Override
	protected void onPause()
	{
		AppMain._imageFileTemporaryTaskFinish = null;
		AppMain._imageFileTemporaryTaskStart = null;
		System.gc();
		super.onPause();
	}

	private ProgressDialog _progressDialog = null;

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
		case AppMain.DIALOG_DOWNLOAD_PROGRESS:
			_progressDialog = new ProgressDialog(this);
			_progressDialog.setMessage(getString(R.string.textMessageDownloadFile));
			_progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			_progressDialog.setCancelable(true);
			_progressDialog.show();
			return _progressDialog;
		default:
			return null;
		}
	}

	@Override
	protected void onDestroy()
	{
		AppMain._imageFileTemporaryTaskFinish = null;
		AppMain._imageFileTemporaryTaskStart = null;
		AppMain._imageFileView = null;
		AppMain.hideAllDialog();
		System.gc();
		super.onDestroy();
	}

	public void processDialogListChoosingImage(int position)
	{
		switch (position)
		{
		case AppMain.IMAGE_BROWSE:
			if (!AppMain.isSdCardPresent())
			{
				AppMain.showAlert(this, R.string.textErrorSDCardNotAvailable,
						false);
			}
			else
			{
				AppMain.showFileChooser(this, AppMain.REQUEST_CHOOSE_FILE_IMAGE);
			}
			break;
		case AppMain.IMAGE_TAKE_CAMERA:
			// Intent intent = new Intent(this, CameraActivity.class);
			// startActivityForResult(intent, AppMain.REQUEST_CAMERA);

			AppMain.openCamera(this);
			break;
		default:
			break;
		}
	}

	private void refreshListComments()
	{

		AppMain.debug("refresh comments!length=" + AppMain._listComments.size());
		_buttonTabListComments.setText(String.format(
				getString(R.string.textListComments),
				AppMain._listComments.size()));
		_listViewItemCommentAdapter = new ListItemCommentAdapter(
				DetailTaskActivity.this, AppMain._listComments);
		_listViewItemCommentAdapter.notifyDataSetChanged();
		_listViewTaskComments.invalidateViews();
	}

	private void showProgressBar()
	{
		AppMain.showProgress(this);
		enableAllClick(true);
	}

	private void enableAllClick(boolean enable)
	{
		_buttonImageFinish.setClickable(enable);
		_buttonImageStart.setClickable(enable);
		_buttonTabDetail.setClickable(enable);
		_buttonTabGuild.setClickable(enable);
		_buttonTabListComments.setClickable(enable);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		AppMain.debug("detai task - window changed");
		if (AppMain._isDoneLoading)
		{
			AppMain.debug("detai task - window changed after done download");
			switch (AppMain._codeResultService)
			{
			case SUCCESS_GET_COMMENTS:
				refreshListComments();
				break;
			case SUCCESS_FINISH_TASK:
				AppMain.showAlert(this, R.string.textFinishTaskSuccess, false);
				if (AppMain._imageFileTemporaryTaskFinish != null)
				{
					AppMain.getCurrentTask().setImageFileFinish(
							AppMain._imageFileTemporaryTaskFinish);
				}

				AppMain.getCurrentTask().setStatus(Task.STATUS_FINISH);
				_textDateActualFinish.setText(AppMain.getCurrentTask().getDateActualFinish());

				if (Config.USE_DATABASE)
				{
					TaskSQLite taskSQLite = new TaskSQLite(
							DetailTaskActivity.this);
					taskSQLite.update(AppMain.getCurrentTask());
				}

				processImage();

				_buttonImageFinishAgain.setVisibility(View.GONE);

				break;
			case SUCCESS_START_TASK:
				AppMain.showAlert(this, R.string.textStartTaskSuccess, false);
				if (AppMain._imageFileTemporaryTaskStart != null)
				{
					AppMain.getCurrentTask().setImageFileStart(
							AppMain._imageFileTemporaryTaskStart);
				}

				AppMain.getCurrentTask().setStatus(Task.STATUS_IN_PROCESS);
				_textDateActualStart.setText(AppMain.getCurrentTask().getDateActualStart());

				if (Config.USE_DATABASE)
				{
					TaskSQLite taskSQLite = new TaskSQLite(
							DetailTaskActivity.this);
					taskSQLite.update(AppMain.getCurrentTask());
				}

				processImage();

				_buttonImageStartAgain.setVisibility(View.GONE);

				break;
			case FAIL_FINISH_TASK:
			case FAIL_START_TASK:
				AppMain.showAlert(this, R.string.textFail, false);
				break;
			case ERROR_OUT_OF_MEMORY:
				AppMain.showAlert(this,
						R.string.textErrorFileTooLargeCanNotLoad, true);
				break;
			default:
				break;
			}
			AppMain._codeResultService = CodeResult.NONE;
			AppMain._isDoneLoading = false;
			enableAllClick(true);
		}

		switch (DownloadFile._errorCode)
		{
		case DownloadFile.ERROR_CONNECTION:
			AppMain.showAlert(this, R.string.textErrorNetwork, false);
			break;

		case DownloadFile.ERROR_URL_NOT_EXIST:
			AppMain.showAlert(this, R.string.textErrorURLNotExist, false);
			break;

		case DownloadFile.ERROR_FILE_CREATE:
			AppMain.showAlert(this, R.string.textErrorFileNotCreated, false);
			break;

		case DownloadFile.STATUS_SUCCESS:
			AppMain.showAlert(
					this,
					getString(R.string.textMessageDownloadFileSuccess)
							+ ": "
							+ AppMain.getCurrentTask().getFileAttachment().getPath()
							+ "/"
							+ AppMain.getCurrentTask().getFileAttachment().getName(),
					false);
			break;
		default:
			break;
		}
		DownloadFile._errorCode = DownloadFile.STATUS_NONE;

		super.onWindowFocusChanged(hasFocus);
	}

}
